import json
from datetime import datetime


def debug_json(obj, title=None):
    """
    将任何对象转换为格式化的JSON并打印出来

    参数:
        obj: 要打印的对象
        title: 可选的标题

    用法:
        debug_json(my_object, "My Object")
    """
    # 处理SQLAlchemy模型对象
    if hasattr(obj, 'to_dict'):
        data = obj.to_dict()
    # 处理SQLAlchemy查询结果列表
    elif isinstance(obj, list) and len(obj) > 0 and hasattr(obj[0], 'to_dict'):
        data = [item.to_dict() for item in obj]
    # 处理分页结果
    elif isinstance(obj, dict) and 'data' in obj and isinstance(obj['data'], list):
        if len(obj['data']) > 0 and hasattr(obj['data'][0], 'to_dict'):
            data = {
                **{k: v for k, v in obj.items() if k != 'data'},
                'data': [item.to_dict() for item in obj['data']]
            }
        else:
            data = obj
    else:
        data = obj

    # 添加时间戳
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # 打印标题和时间戳
    if title:
        print(f"\n===== {title} [{timestamp}] =====")
    else:
        print(f"\n===== DEBUG JSON [{timestamp}] =====")

    # 打印格式化的JSON
    try:
        print(json.dumps(data, ensure_ascii=False, indent=2, default=str))
        print("=" * 40)
    except TypeError as e:
        print(f"无法序列化为JSON: {e}")
        print(f"原始对象: {data}")
        print("=" * 40)